import {
  addPlatFormAuth,
  deletePlatFormAuth,
  editPlatFormAuth,
  selectAllAuthCate,
  mSelectPlatFormAuthByPage
} from '@/api/conf'
import { FormInstance } from 'ant-design-vue'
import { PropType } from 'vue'
import './components.less'
import { CoustomTableFn } from '@/components/table'
import { message } from '@/libs/global/antDesignVue'

/**状态数据 */
interface Conf_api_state {
  /**接口类型 */
  apiType_list: SysDict.Item[]
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: string
    /**弹窗 标题*/
    title: string
    /** 弹窗 修改 数据源 */
    edit_source: User.PlatFormAuth
    add_source: User.AddPlatFormAuthDataSource
  }
  table: CTable<User.PlatFormAuth>
  search: {
    authName: string
    roleCode: string | undefined
  }
}
let conf_api_state = reactive<Conf_api_state>({
  apiType_list: [],
  modal: {
    visible: false,
    type: '',
    title: '',
    edit_source: {
      authCateCode: '',
      authCateName: '',
      authDesc: '',
      authId: '',
      authMethod: '',
      authName: ''
    },
    add_source: {
      authCateCode: '',
      authDesc: '',
      authMethod: '',
      authName: ''
    }
  },
  table: {
    dataSource: [],
    loading: false,
    pagination: {
      page: 1,
      size: 20
    },
    total: 0,
    onPaginatiChange({ page, size }) {
      let { pagination } = toRefs(conf_api_state.table)
      pagination.value.page = page
      pagination.value.size = size
      getTableDatas()
    }
  },
  search: {
    authName: '',
    roleCode: undefined
  }
})

/**获取表格数据 */
export async function getTableDatas(data?: any) {
  let { dataSource, pagination, total: tableTotal } = toRefs(conf_api_state.table)
  let { search } = toRefs(conf_api_state)
  if (search.value.roleCode === undefined) {
    return
  }
  let defaultData: {
    authName: AuthName
    roleCode: RoleCode
  } & Paging = {
    page: pagination.value.page,
    size: pagination.value.size,
    roleCode: search.value.roleCode,
    authName: search.value.authName
  }
  if (data) Object.assign(defaultData, data)
  mSelectPlatFormAuthByPage(defaultData)
    .then(res => {
      let { list, total } = res.data
      dataSource.value = list
      tableTotal.value = total
    })
    .catch(err => {})
}

/**获取所有权限类别 */
const getAllAuthCate = async () => {
  let { apiType_list } = toRefs(conf_api_state)
  let res = await selectAllAuthCate().catch(err => {})
  if (res) {
    apiType_list.value = res.data
  }
}

/**重置搜索条件 页码变为1 */
const handle_search_reset = () => {
  let { search } = toRefs(conf_api_state)
  let { pagination } = toRefs(conf_api_state.table)

  Object.keys(search.value).forEach(key => {
    search.value[key as keyof typeof search.value] = ''
  })

  pagination.value.page = 1
  getTableDatas()
}
/**左侧搜索区域 头部*/
export const ViewLeftNav = defineComponent({
  name: 'ViewLeftNav',
  setup(props, { emit }) {
    let { authName } = toRefs(conf_api_state.search)
    let { pagination } = toRefs(conf_api_state.table)
    const handle_enter_event = (e: KeyboardEvent) => {
      pagination.value.page = 1
      getTableDatas()
    }
    return () => (
      <div class='w-full h-full flex justify-center items-center overflow-x-auto'>
        <a-input
          class='w-full h-full'
          placeholder='输入权限名称,回车查询'
          v-model={[authName.value, 'value']}
          onPressEnter={(e: KeyboardEvent) => handle_enter_event(e)}
          allow-clear={true}
        ></a-input>
      </div>
    )
  }
})

/** 左侧搜索区域 条件选择区域 */
export const ViewLeftFilter = defineComponent({
  name: 'ViewLeftFilter',
  setup() {
    let { search, apiType_list } = toRefs(conf_api_state)
    onMounted(() => {
      getAllAuthCate()
    })
    function handle_authCate_checked(data: AuthCateName) {
      search.value.roleCode = data
    }
    return () => (
      <div class='h-mainViewcontent viewLeftFilter'>
        {/* <label for="viewLeftFilter">
          <input
            type="radio"
            name="viewLeftFilter"
            id="viewLeftFilter"
            checked={search.value.roleCode === ''}
            class="hidden input_acitve"
          ></input>
          <div
            class="viewLeftFilter-line leading-6  flex justify-between items-center text-sm truncate cursor-pointer py-2 hover:bg-primary_light"
            onClick={() => handle_authCate_checked('')}
          >
            <div class="viewLeftFilter-icon w-1/12 h-6">
              <i class="iconfont"></i>
            </div>
            <div class="viewLeftFilter-label w-5/12 h-6">全部</div>
            <div class="viewLeftFilter-value w-5/12 h-6  text-right pr-1 text-info text-xs">
              查询所有类型
            </div>
          </div>
        </label>
        {apiType_list.value.map((type, idx) => (
          <label for={'viewLeftFilter' + idx}>
            <input
              type="radio"
              name="viewLeftFilter"
              id={'viewLeftFilter' + idx}
              checked={search.value.roleCode === type.  authCateCode}
              class="hidden input_acitve"
            ></input>
            <div
              class="viewLeftFilter-line leading-6  flex justify-between items-center text-sm truncate cursor-pointer py-2 hover:bg-primary_light"
              onClick={() => handle_authCate_checked(type.authCateName)}
            >
              <div class="viewLeftFilter-icon w-1/12 h-6">
                <i class="iconfont"></i>
              </div>
              <div class="viewLeftFilter-label w-5/12 h-6">
                {type.authCateName}
              </div>
              <div class="viewLeftFilter-value w-5/12 h-6  text-right pr-1 text-info text-xs"></div>
            </div>
          </label>
        ))} */}
      </div>
    )
  }
})

/**左侧搜索区域 */
export const ViewLeftFooter = defineComponent({
  name: 'ViewLeftFooter',
  setup(props, { emit }) {
    return () => (
      <div class='w-full h-full flex justify-end items-center '>
        <a-button type='primary' class='mx-2' onClick={handle_search_reset}>
          重置
        </a-button>
        <a-button type='primary' class='mx-2' onClick={getTableDatas}>
          查询
        </a-button>
      </div>
    )
  }
})

/**数据表格 头部 操作栏 */
export const MainViewNav = defineComponent({
  setup() {
    let { visible, title, type } = toRefs(conf_api_state.modal)
    const handle_add_btn_click = () => {
      visible.value = true
      type.value = 'addAuth'
      title.value = '添加权限'
    }
    return () => (
      <div class='h-full bg-white px-4 flex justify-start items-center'>
        <a-button type='primary' onClick={handle_add_btn_click}>
          添加权限
        </a-button>
      </div>
    )
  }
})

/**数据表格 操作栏 */
const TypeHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<User.PlatFormAuth>,
      default: {}
    }
  },
  setup(props) {
    let { visible, title, type, edit_source } = toRefs(conf_api_state.modal)
    const handle_type_edit_btn_click = () => {
      visible.value = true
      type.value = 'editAuth'
      title.value = '修改权限信息'
      edit_source.value = props.record
    }
    const handle_delete_click = async () => {
      await deletePlatFormAuth({ authId: props.record.authId }).catch(() => {})
      getTableDatas()
    }
    return () => (
      <div>
        <span
          class='mr-2 text-primary border-b cursor-pointer'
          onClick={handle_type_edit_btn_click}
        >
          编辑
        </span>
        <a-popconfirm
          title={`确认删除权限: ${props.record.authName} 吗?`}
          placement='topRight'
          ok-text='确认'
          cancel-text='取消'
          onConfirm={handle_delete_click}
          onCancel={() => {}}
        >
          <span class='mr-2 text-primary border-b cursor-pointer'>删除</span>
        </a-popconfirm>
      </div>
    )
  }
})

/**数据表格 */
const CoustomTable = CoustomTableFn<User.PlatFormAuth>()
export const MainViewContentTable = defineComponent({
  name: 'MainViewContentTable',
  setup(props) {
    let { dataSource, loading, total, onPaginatiChange } = toRefs(conf_api_state.table)
    let { page, size } = toRefs(conf_api_state.table.pagination)

    let columns: CColumn<User.PlatFormAuth>[] = [
      {
        title: '权限名称',
        dataIndex: 'authName',
        ellipsis: true
      },
      {
        title: '方法',
        dataIndex: 'authMethod',
        ellipsis: true
      },
      {
        title: '权限类别',
        dataIndex: 'authCateName',
        ellipsis: true
      },
      {
        title: '备注',
        dataIndex: 'authDesc',
        ellipsis: true
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true
      }
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey='authId'
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value
        }}
        onPaginationChange={data => onPaginatiChange.value(data)}
      >
        {{
          util: (record: User.PlatFormAuth) => <TypeHandleBtn record={record}></TypeHandleBtn>
        }}
      </CoustomTable>
    )
  }
})

/**弹窗 表单 添加权限用 */
const AddFormOfModal = defineComponent({
  name: 'AddFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let formRef = ref<FormInstance>()
    let { add_source } = toRefs(conf_api_state.modal)
    let { apiType_list } = toRefs(conf_api_state)
    let onLoading = ref(false)
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      // console.log(add_source.value)
      onLoading.value = true
      await addPlatFormAuth(add_source.value).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', add_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      onLoading.value = false
      formRef.value?.resetFields()
      emit('finish')
    }

    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='addAuth'
        model={add_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='权限名称' name='authName'>
          <a-input v-model={[add_source.value.authName, 'value']} />
        </a-form-item>
        <a-form-item label='方法' name='authMethod'>
          <a-input v-model={[add_source.value.authMethod, 'value']} />
        </a-form-item>
        <a-form-item label='权限类别' name='  authCateCode'>
          <a-select
            v-model={[add_source.value.authCateCode, 'value']}
            options={apiType_list.value}
            fieldNames={{
              label: 'dictName',
              value: 'dictCode'
            }}
          ></a-select>
        </a-form-item>
        <a-form-item label='备注' name='authDesc'>
          <a-input v-model={[add_source.value.authDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button
            type='primary'
            class='float-right mx-4'
            html-type='submit'
            loading={onLoading.value}
          >
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})

/**弹窗 表单 修改权限用 */
const EditFormOfModal = defineComponent({
  name: 'EditFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let { apiType_list } = toRefs(conf_api_state)
    let { edit_source } = toRefs(conf_api_state.modal)
    let formRef = ref<FormInstance>()

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      let currentApiType = apiType_list.value.filter(
        data => data.dictCode === edit_source.value.authCateName
      )[0]
      let authCateCode = currentApiType.dictCode
      await editPlatFormAuth({
        authCateCode: authCateCode,
        authDesc: edit_source.value.authDesc,
        authId: edit_source.value.authId,
        authMethod: edit_source.value.authMethod,
        authName: edit_source.value.authName
      }).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', edit_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='editSysdictType'
        model={edit_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='权限名称' name='authName'>
          <a-input v-model={[edit_source.value.authName, 'value']} />
        </a-form-item>
        <a-form-item label='方法' name='authMethod'>
          <a-input v-model={[edit_source.value.authMethod, 'value']} />
        </a-form-item>
        <a-form-item label='权限类别' name='  authCateCode'>
          <a-select
            v-model={[edit_source.value.authCateName, 'value']}
            options={apiType_list.value}
            fieldNames={{
              label: 'dictName',
              value: 'dictCode'
            }}
          ></a-select>
        </a-form-item>
        <a-form-item label='备注' name='authDesc'>
          <a-input v-model={[edit_source.value.authDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button type='primary' class='float-right mx-4' html-type='submit'>
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})

/**弹窗 */
export const MainViewModel = defineComponent({
  setup(props, { emit }) {
    let { visible, type, title } = toRefs(conf_api_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = ''
      title.value = ''
      getTableDatas()
    }
    return () => {
      let dynamicCom
      switch (type.value) {
        case 'addAuth':
          dynamicCom = <AddFormOfModal onFinish={handle_form_finish}></AddFormOfModal>
          break
        case 'editAuth':
          dynamicCom = <EditFormOfModal onFinish={handle_form_finish}></EditFormOfModal>
          break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  }
})
